/**
 * WeChat Work Environment Configuration
 * 企业微信环境配置
 */
const WECHAT_CONFIG = {
  // WeChat Work configuration (基于实际部署地址)
  // 企业微信配置信息
  CORP_ID: 'ww87bbc3050f7d58de',
  AGENT_ID: '1000015',
  
  // API Configuration
  // API配置
  API_BASE_URL: process.env.NODE_ENV === 'production' 
    ? 'https://feoa.gfelz.com:6731/refundtaskapi/api'
    : 'https://feoa.gfelz.com:6731/refundtaskapi/api',
    
  // 企业微信授权URL
  OAUTH_URL: 'https://open.weixin.qq.com/connect/oauth2/authorize',
  // 企业微信扫码登录URL
  QRCONNECT_URL: 'https://open.work.weixin.qq.com/wwopen/sso/qrConnect'
}

/**
 * Check if running in WeChat Work environment
 * 检测是否在企业微信环境中
 * @returns {boolean} True if in WeChat Work environment
 */
export const isWeChatWork = () => {
  const ua = navigator.userAgent.toLowerCase()
  const isWxWork = ua.includes('wxwork')
  const isMicroMessenger = ua.includes('micromessenger')
  
  console.log('用户代理:', ua)
  console.log('是否企业微信:', isWxWork)
  console.log('是否微信:', isMicroMessenger)
  
  return isWxWork || isMicroMessenger
}

/**
 * 检测是否在微信环境中（非企业微信）
 */
export const isWeChat = () => {
  const ua = navigator.userAgent.toLowerCase()
  return ua.includes('micromessenger') && !ua.includes('wxwork')
}

/**
 * 检测是否在移动设备上
 */
export const isMobile = () => {
  const ua = navigator.userAgent.toLowerCase()
  return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ua)
}

/**
 * 获取URL参数
 */
export const getUrlParam = (name) => {
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get(name)
}

/**
 * 构建企业微信授权URL
 */
export const buildWeChatWorkAuthUrl = (redirectUri, state = 'STATE') => {
  const params = new URLSearchParams({
    appid: WECHAT_CONFIG.CORP_ID,
    agentid: WECHAT_CONFIG.AGENT_ID,
    redirect_uri: encodeURIComponent(redirectUri),
    response_type: 'code',
    scope: 'snsapi_base',
    state: state
  })
  
  return `${WECHAT_CONFIG.OAUTH_URL}?${params.toString()}`
}

/**
 * 处理企业微信授权回调
 */
export const handleWeChatWorkCallback = () => {
  const code = getUrlParam('code')
  const state = getUrlParam('state')
  const error = getUrlParam('error')
  
  return {
    code,
    state,
    error,
    hasCode: !!code,
    hasError: !!error
  }
}

/**
 * 跳转到企业微信授权页面
 */
export const redirectToWeChatWorkAuth = (authUrl) => {
  if (typeof window !== 'undefined') {
    window.location.href = authUrl
  }
}

/**
 * 企业微信环境检测和处理
 */
export const initWeChatWorkEnvironment = () => {
  const isWxWork = isWeChatWork()
  const isMobileDevice = isMobile()
  
  console.log('企业微信环境检测:', {
    isWeChatWork: isWxWork,
    isMobile: isMobileDevice,
    userAgent: navigator.userAgent
  })
  
  return {
    isWeChatWork: isWxWork,
    isMobile: isMobileDevice,
    shouldUseWeChatWorkLogin: isWxWork
  }
}

/**
 * 错误处理
 */
export const handleWeChatWorkError = (error, defaultMessage = '企业微信操作失败') => {
  console.error('企业微信错误:', error)
  
  let message = defaultMessage
  let code = ''
  
  if (typeof error === 'string') {
    message = error
  } else if (error && error.response) {
    message = error.response.data?.message || error.message || defaultMessage
    code = error.response.status?.toString() || ''
  } else if (error && error.message) {
    message = error.message
  }
  
  return {
    message,
    code,
    originalError: error
  }
}

// 本地存储相关
export const STORAGE_KEYS = {
  WECHAT_WORK_TOKEN: 'wechat_work_token',
  WECHAT_WORK_USER: 'wechat_work_user',
  WECHAT_WORK_STATE: 'wechat_work_state'
}

/**
 * 保存企业微信状态
 */
export const saveWeChatWorkState = (state) => {
  try {
    localStorage.setItem(STORAGE_KEYS.WECHAT_WORK_STATE, JSON.stringify(state))
  } catch (error) {
    console.error('保存企业微信状态失败:', error)
  }
}

/**
 * 获取企业微信状态
 */
export const getWeChatWorkState = () => {
  try {
    const state = localStorage.getItem(STORAGE_KEYS.WECHAT_WORK_STATE)
    return state ? JSON.parse(state) : null
  } catch (error) {
    console.error('获取企业微信状态失败:', error)
    return null
  }
}

/**
 * 清除企业微信状态
 */
export const clearWeChatWorkState = () => {
  try {
    localStorage.removeItem(STORAGE_KEYS.WECHAT_WORK_STATE)
    localStorage.removeItem(STORAGE_KEYS.WECHAT_WORK_TOKEN)
    localStorage.removeItem(STORAGE_KEYS.WECHAT_WORK_USER)
  } catch (error) {
    console.error('清除企业微信状态失败:', error)
  }
}























export default {
  WECHAT_CONFIG,
  isWeChatWork,
  isWeChat,
  isMobile,
  getUrlParam,
  buildWeChatWorkAuthUrl,
  handleWeChatWorkCallback,
  redirectToWeChatWorkAuth,
  initWeChatWorkEnvironment,
  handleWeChatWorkError,
  saveWeChatWorkState,
  getWeChatWorkState,
  clearWeChatWorkState,
  STORAGE_KEYS
}